package supercafe.more;

import java.util.Vector;

import supercafe.core.MakeOrderDetailsScreen;
import supercafe.core.R;
import supercafe.defines.URLs;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class MainScreen extends Activity implements Finish{
	//private  Vector<Area> areasWithTables = new Vector<Area>();
	private Spinner spinner;
	private DataGetter datagetter;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout2);
        // add action for exit button
        final Button bt_ex = (Button) findViewById(R.id.bt_ex);
        bt_ex.setOnClickListener(new OnClickListener(){
			public void onClick(View v) {
				// TODO Auto-generated method stub
				AlertDialog.Builder builder = new AlertDialog.Builder(MainScreen.this);
				builder.setMessage("Bạn chắc chắn muốn đăng xuất?")
				       .setCancelable(false)
				       .setPositiveButton("Có", new DialogInterface.OnClickListener() {
				    	   
				           public void onClick(DialogInterface dialog, int id) {
				        	   	Intent i = new Intent(MainScreen.this, dangnhap.class);
								startActivity(i);
				           }
				       })
				       .setNegativeButton("Không", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				                dialog.cancel();
				           }
				       });
				AlertDialog alert = builder.create();
				alert.show();
				
			}
        });
        // add action for capnhat button
        final Button bt_capnhat = (Button) findViewById(R.id.bt_capnhatban);
        bt_capnhat.setOnClickListener(new OnClickListener() {			
			public void onClick(View v) {
				// TODO Auto-generated method stub
		        loadData(true);
			}
		});
        loadData(false);
    }
    
    private void init(){
    	int areaSelectedIndex = -1;
    	if(spinner==null){
    		spinner = (Spinner) findViewById(R.id.spinner);
    	}else{
    		areaSelectedIndex = spinner.getSelectedItemPosition();
    	}    	
        ArrayAdapter<Area> areaAdapter = new ArrayAdapter<Area>(this,android.R.layout.simple_spinner_item,Area.areasWithTables);
        areaAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(areaAdapter);
        if(areaSelectedIndex!=-1){
        	spinner.setSelection(areaSelectedIndex,true);
        }
        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {		
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				showTable(arg2);
				
			}
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub				
			}
		});
    }
    
    public void showTable(final int indexSelected){
    	// get area
    	Area areaSelected = Area.areasWithTables.get(indexSelected);
    	// get all table
    	Vector<Table> tables = areaSelected.getTables();
    	// ------- add table to screen -------------
    	TableLayout tableLayout = (TableLayout)findViewById(R.id.tb1);
    	// remove all element in table layout
    	tableLayout.removeAllViews();
    	
    	// add table to tablelayout
        int len = tables.size();
        int count = 0;
        for(int row=0;row<Math.ceil(len/4)+1;row++){
        	TableRow tr = new TableRow(this);
        	TableRow.LayoutParams params = new TableRow.LayoutParams();
        	params.width=LayoutParams.FILL_PARENT;
        	tr.setLayoutParams(params);
        	for(int col=0;col<4;col++){
        		if(count>=len)
        		{
        			break;
        		}
        		Button bt = new Button(this);
        		Table currentTable = tables.get(count);
	        	bt.setText(currentTable.getTableName());
	        	params = new TableRow.LayoutParams();
	        	params.column=col + 1;
	        	bt.setLayoutParams(params);
	        	bt.setClickable(true);
	        	bt.setTag(count);
	        	if(currentTable.isUsed()){
	        		bt.setTextColor(Color.RED);
	        	}
	        	if(currentTable.isOrdered()){
	        		bt.setTextColor(Color.MAGENTA);
	        	}
	        	if(currentTable.isPrepared()){
	        		bt.setTextColor(Color.BLUE);
	        	}	        	
	        	bt.setOnClickListener(new OnClickListener(){	        	
	        		public void onClick(View arg0) {
	    				Intent i = new Intent(MainScreen.this, TasksScreen.class);
	    				Bundle b = new Bundle();
	    				try{
	    					b.putInt("tablePosition", Integer.parseInt(arg0.getTag().toString()));
	    					b.putInt("areaPosition", indexSelected);
	    				}catch (Exception e) {
						}
	    				i.putExtras(b);
	    				startActivity(i);
	        			//Toast.makeText(Manhinhchinh.this,arg0.getTag()+"", Toast.LENGTH_LONG).show();
	        		}    	
	            });
	        	tr.addView(bt);
	        	count++;
        	}
        	tableLayout.addView(tr);
        }
    }
    
    private void loadData(boolean restrict){
    	// nếu chưa có dữ liệu thì load data
    	if(restrict || Area.areasWithTables==null){
	    	// load data from server
	    	datagetter = new DataGetter(this, this);
	    	String link = URLs.AREAS_TABLES +Profile.sessionId;
	    	datagetter.execute(link);
    	}else{
    		init();
    	}
    }
    
	public void doFinish() {
		// TODO Auto-generated method stub
		//Toast.makeText(this,datagetter.getResponseResult() , Toast.LENGTH_LONG).show();
		// tach du~ lieu
		String xmlResponse = datagetter.getResponseResult();
		Area.areasWithTables = XMLHandler.getAreasWithTable(xmlResponse);
        init();
		// add các listenner và show dữ liệu
		
	}
}
